/**
 * 平台管理系统--学生管理
 * @author 卢凤丹
 */
import {Component, OnInit} from '@angular/core';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import {SelfValidators} from '../../../utils/self.validators';
import {PageEntity} from '../../../core/domain/page.entity';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Observable, Observer} from 'rxjs';
import {StorageUtil} from '../../../utils/storage.util';
import {StudentService} from './student.service';
import {DatePipe} from '@angular/common';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {OtherUtil} from '../../../utils/other.util';
import {PaginationUtils} from '../../../utils/paginationUtils';
import {PostDown} from '../../../utils/postdown';

@Component({
    selector: 'app-student',
    templateUrl: './student.component.html',
    styleUrls: ['./student.component.scss'],
    providers: [StudentService, PostDown]
})
export class StudentComponent implements OnInit {
    roleManager = 1;
    searchName:string = '';
    searchNum:string = '';
    pageInfo: PageEntity = new PageEntity();
    pageInfoCampus: PageEntity = new PageEntity();
    pageInfoStudentType: PageEntity = new PageEntity();
    allList: StudentObj[] = [];
    displayList:Array<any> = [];
    mapOfCheckedId: { [key: string]: boolean } = {};
    isAllCheck:boolean = false;
    isIndeterminate:boolean = false;

    isAdd:boolean = true;
    showAddModal:boolean = false; // 新增弹框
    showModal:boolean = false; // 产看弹框
    modalTitle = '新增';
    list:Array<any> = [];
    // 图片上传
    headerInfo = null;
    uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
    validateForm: FormGroup;
    loading:boolean = false;
    avatarUrl: string;
    userPhoto = 'assets/user/photo0.png';
    nodes:Array<any> = [];
    searchValue: any;
    className: any;
    collegeName: any;
    // 表格上的过滤
    filterSexArr:Array<{text:string,value:number}> = [
        {
            text: '男',
            value: 0
        },
        {
            text: '女',
            value: 1
        }
    ];
    // 学生类型
    filterTypeArr: { text: string; value: number }[] = [
        {
            text: '高职',
            value: 3
        },
        {
            text: '本科生',
            value: 0
        },
        {
            text: '研究生',
            value: 1
        },
        {
            text: '博士生',
            value: 2
        }
    ];
    filterCollegeArr:Array<any> = [];
    filterMajorArr:Array<any> = [];
    filterClassArr:Array<any> = [];
    // 查看使用数据
    studentShow: StudentObj = new StudentObj();

    canDelete = true;

    // excel导入
    fileListImport: UploadFile[] = [];
    showExcelModal:boolean = false;
    headerInfoExcel = null;

    // 导入的Excel 名称
    importExcelName:string = '';
    previewImage: string | undefined = '';
    previewVisible:boolean = false;
    showUploadList = {
        showPreviewIcon: true,
        showRemoveIcon: true,
        hidePreviewIconInNonImage: true
    };
    campusList = []; // 校区下拉框
    studentTypeList = []; // 学生类型下拉框
    tableObj = {};
    xqhId = '';

    constructor(
        private service: StudentService,
        private message: NzMessageService,
        private datePipe: DatePipe,
        private fb: FormBuilder,
        private postDown: PostDown
    ) {
    }

    ngOnInit() {
        this.getPage();
        this.initForm();
        // 图片上传头部
        this.headerInfo = StorageUtil.getFileHeader();
        this.collegeList();
        // 图片上传头部
        this.headerInfoExcel = StorageUtil.getFileHeader();
        // this.roleManager = StorageUtil.getLocalStorage('roleManager');
        const multiSortArr = [
          {
            field: 'type',
            order: 1
          },
          {
            field: 'orderLevel',
            order: 1
          }
        ];
        this.pageInfoCampus.filters['type'.toString()] = {
          matchMode: 'contains',
          value: 'school-type',
          whereType: 'AND'
        };
        this.pageInfoStudentType.filters['type'.toString()] = {
          matchMode: 'contains',
          value: 'edu-sort',
          whereType: 'AND'
        };
        this.pageInfoCampus.multiSortMeta = multiSortArr;
        this.pageInfoStudentType.multiSortMeta = multiSortArr;
        this.getCampusList(this.pageInfoCampus);
        this.getStudentTypeList(this.pageInfoStudentType);
    }

    initForm() {
        this.validateForm = this.fb.group({
            name: [null, [Validators.required]],
            number: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(20)]],
            xqmc: ['', [Validators.required]],
            collegeId: ['', [Validators.required]],
            majorId: ['', [Validators.required]],
            classId: ['', [Validators.required]],
            schoolTime: [null, []],
            photo: [null, []],
            id: [null, []],
            sex: [0, []],
            telphone: [null, []],
            type: [null, []],
            idcard: [null, [SelfValidators.isIdCardNo]],
            email: [null, [SelfValidators.emailValidator]]
        });
    }

    /**
     * 获取校区下拉框
     */
    getCampusList(page: PageEntity) {
      this.service.getDicList(page).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.campusList = res.datas.data;
        }
      });
    }

    /**
     * 获取学生类型下拉框
     */
    getStudentTypeList(page: PageEntity) {
        this.service.getDicList(page).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.studentTypeList = res.datas.data;
            this.studentTypeList.map(item => {
              this.tableObj[item.keyValue] = item.keyCode;
            });
          }
        });
      }

    checkDelete(): void {
        this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
    }

    // 表格过滤
    filterSome(event, flag) {
        if (event.length > 0) {
            this.pageInfo.first = 1;
            this.pageInfo.filters[flag] = {
                matchMode: 'in',
                value: event.join(','),
                whereType: FilterTypeEnum.AND
            };
        } else {
            this.pageInfo.filters[flag] = undefined;
        }
        this.getPage();
    }

    // 性别转换
    transformSex(par) {
        let aa = '';
        switch (par) {
            case 0:
                aa = '男';
                break;
            case 1:
                aa = '女';
                break;
        }
        return aa;
    }

    // 学生类型转换
    transformType(par) {
        let bb = '';
        switch (par) {
            case 0:
                bb = '本科生';
                break;
            case 1:
                bb = '研究生';
                break;
            case 2:
                bb = '博士生';
                break;
            case 3:
                bb = '高职';
                break;
        }
        return bb;
    }

    // 点击查询
    clickSearch() {
        this.pageInfo.first = 1;
        this.dealPageFilterFn(this.pageInfo, this.searchName, 'name', FilterEnum.CONTAINS, FilterTypeEnum.AND);
        this.dealPageFilterFn(this.pageInfo, this.searchNum, 'number', FilterEnum.CONTAINS, FilterTypeEnum.AND);
        this.getPage();
    }

    dealPageFilterFn(pageParam: PageEntity, currVal: any, strVal: string, filterMode: any, typeMode: any): void {
        currVal ? pageParam.filters[strVal.toString()] = {matchMode: filterMode, value: currVal, whereType: typeMode} :
            pageParam.filters[strVal.toString()] = undefined;
    }

    // 点击重置
    resetSearch() {
        this.searchName = null;
        this.searchNum = null;
        this.pageInfo = new PageEntity();
        this.pageInfo.first = 1;
        this.pageInfo.filters['number'.toString()] = undefined;
        this.pageInfo.filters['name'.toString()] = undefined;
        this.getPage();
    }

    // 查询部门列表
    collegeList() {
        this.service.getCollege().subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.filterCollegeArr = res.datas;
            }
        });
    }

    // 部门change
    collegeChange(event) {
        if (event) {
            this.filterMajorArr = null;
            this.filterClassArr = null;
            this.validateForm.get('majorId').setValue('');
            this.majorList(event);
        }
    }

    /**
     * 查询专业
     * @param id 部门
     */
    majorList(id) {
        this.service.getMajor(id).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.filterMajorArr = res.datas;
            }
        });
    }

    /**
     * 专业，班级搜索
     * @param filed 字段：部门，专业
     * @param value 输入的值
     */
    titleSearch(filed: string, value: string): void {
        if (value) {
            this.pageInfo = new PageEntity();
            this.pageInfo.filters[filed] = PaginationUtils.filters(value, FilterEnum.CONTAINS);
            this.getPage();
        }
    }

    /**
     * 重置
     * @param field 字段
     */
    resetFilter(field: string): void {
        delete this.pageInfo.filters[field];
        this.getPage();
    }

    /**
     * 排序
     * @param sort 排序值
     * @flag true表示正式考试，false 表示测试考试
     */
    sort(sort: { key: string; value: string }): void {
        this.pageInfo = PaginationUtils.sort(this.pageInfo, sort);
        this.getPage();
    }


    // 专业change
    majorChange(event) {
        if (event) {
            this.filterClassArr = null;
            this.validateForm.get('classId').setValue('');
            this.classList(event);
        }
    }

    // 查询班级
    classList(id) {
        this.service.getClass(id).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.filterClassArr = res.datas;
            }
        });
    }

    // 分页查询
    getPage() {
        this.service.page(this.pageInfo).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.allList = res.datas.data;
                this.pageInfo.totalRecords = res.datas.totalRecords;
            }
        });
    }

    // 第几页
    searchPageIndex(event) {
        this.pageInfo.first = event;
        this.getPage();
    }

    // 每页几条
    searchPageSize(event) {
        this.pageInfo.rows = event;
        this.pageInfo.first = 1;
        this.getPage();
    }

    currentPageDataChange($event): void {
        this.displayList = $event;
        this.refreshStatus();
    }

    refreshStatus(): void {
        this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
        this.isIndeterminate =
            this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
            !this.isAllCheck;
        this.checkDelete();
    }

    checkAll(value: boolean): void {
        this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
        this.refreshStatus();
    }

    // 点击删除一个
    deleteOne(id) {
        this.service.delete([id]).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.message.success(res.message);
                this.mapOfCheckedId = {};
                // this.pageInfo.first = 1;
                this.getPage();
            }
        });
    }

    // 删除所选
    deleteAll() {
        const arr = [];
        for (const val in this.mapOfCheckedId) {
            if (this.mapOfCheckedId[val]) {
                arr[arr.length] = val;
            }
        }
        if (arr.length < 1) {
            this.message.warning('请勾选要删除的数据!');
            return;
        }
        this.service.delete(arr).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.message.success(res.message);
                this.mapOfCheckedId = {};
                this.pageInfo.first = 1;
                this.getPage();
            }
        });
    }

    cancelFn(): void {
        this.canDelete = true;
        this.isAllCheck = false;
        this.mapOfCheckedId = {};
        this.isIndeterminate = false;
    }

    // 点击新增
    clickAdd() {
        this.initForm();
        this.modalTitle = '新增';
        this.isAdd = true;
        this.changePhoto(0);
        this.showAddModal = true;
        this.avatarUrl = null;
        this.filterMajorArr = null;
        this.filterClassArr = null;
    }

    // 男女改变
    changePhoto(event) {
        if (event === 1 || event === '1') {
            this.userPhoto = 'assets/user/photo1.png';
        }
        if (event === 0 || event === '0') {
            this.userPhoto = 'assets/user/photo0.png';
        }
    }

    // 查看-显示图片
    showImgView(obj) {
        return HTTP_BASE_URL + `${SERVERS_NAME.SECURITY_SERVER}source/view/${obj.moduleName}/${obj.fileNewName}`;
    }

    beforeUpload = (file: File) => {
        return new Observable((observer: Observer<boolean>) => {
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!isLt5M) {
                this.message.warning('图片大小不能超过5M!');
                observer.complete();
                return;
            }
            observer.next(isLt5M);
            observer.complete();
        });
    };

    private getBase64(img: File, callback: (img: string) => void): void {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result.toString()));
        reader.readAsDataURL(img);
    }

    // 上传头像
    handleChange(info): void {
        const {file, type} = info;
        if (type === 'success') {
            const {datas, status} = file.response;
            if (status === StatusEnum.SUCCESS) {
                this.getBase64(file.originFileObj, (img: string) => {
                    this.loading = false;
                    this.avatarUrl = img;
                });
                this.message.success('头像上传成功!');
                this.validateForm.get('photo').setValue(datas.id);
            } else {
                this.message.warning(file.response);
            }
        }
    }

    // 新增确认
    handleOk() {
        if (this.validateForm.value.schoolTime) {
            this.validateForm.value.schoolTime = this.datePipe.transform(this.validateForm.value.schoolTime, 'yyyy-MM-dd');
        }
        this.validateForm.value.sex = parseInt(this.validateForm.value.sex, 10);
        this.validateForm.value.type = parseInt(this.validateForm.value.type, 10);
        this.campusList.map(item => {
            if (item.keyCode === this.validateForm.value.xqmc) {
              this.xqhId = item.keyValue;
            }
        });
        this.isAdd ? this.createFn() : this.updateFn();
    }

    updateFn(): void {
        this.service.update({...this.validateForm.value, xqhId: this.xqhId}).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.showAddModal = false;
                this.getPage();
                this.message.success(res.message);
            }
        });
    }

    createFn(): void {
        this.service.create({...this.validateForm.value, xqhId: this.xqhId}).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.showAddModal = false;
                this.getPage();
                this.message.success(res.message);
            }
        });
    }

    // 学生查看
    showStuent(student) {
        this.studentShow = student;
        this.changePhoto(student.sex);
        this.showModal = true;
    }

    // 点击编辑
    editUser(obj) {
        this.modalTitle = '编辑';
        this.isAdd = false;
        this.majorList(obj.collegeId);
        this.classList(obj.majorId);
        this.validateForm.get('name').setValue(obj.name);
        this.validateForm.get('number').setValue(obj.number);
        this.validateForm.get('xqmc').setValue(obj.xqmc);
        this.validateForm.get('collegeId').setValue(obj.collegeId);
        this.validateForm.get('majorId').setValue(obj.majorId);
        this.validateForm.get('classId').setValue(obj.classId);
        this.validateForm.get('schoolTime').setValue(obj.schoolTime);
        this.validateForm.get('sex').setValue(obj.sex);
        this.validateForm.get('telphone').setValue(obj.telphone);
        this.validateForm.get('type').setValue(obj.type);
        this.validateForm.get('idcard').setValue(obj.idcard);
        this.validateForm.get('email').setValue(obj.email);
        this.validateForm.get('photo').setValue(obj.photo);
        this.validateForm.get('id').setValue(obj.id);
        this.showAddModal = true;
        if (obj.photo) {
            this.avatarUrl = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`
                + 'source/view/' + obj.photoSource.moduleName + '/' + obj.photoSource.fileNewName;
        } else {
            this.avatarUrl = null;
            this.changePhoto(obj.sex);
        }
    }

    /**
     * 导入点击
     */
    uploadTable() {
        this.showExcelModal = true;
        this.importExcelName = '';
    }

  /**
   * 重置密码
   */
  resetPassword(data: any) {
    this.service.resetPassword(data.id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success('重置密码成功!');
      } else {
        this.message.error('重置密码失败!');
      }
    });
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
  exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      obj.pager = {};
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfo;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('security-server/dietc/sys/student/exportExcel2', obj);
  }

    /**
     * 下载模板
     */
    exportExclShow() {
        window.location.href = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}` + '/sys/student/downloadModule';
    }

    /**
     * 导入确认
     */
    handleUpload() {
        if (!this.fileListImport || this.fileListImport.length === 0) {
            this.message.warning('请选择上传文件!');
            return;
        }
        const formData = new FormData();
        this.fileListImport.forEach((file: any) => {
            formData.append('file', file);
        });
        // 执行导入
        this.service.importExcel(formData).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.message.success('导入成功!');
                this.showExcelModal = false;
                // 清除导入文件id
                this.importExcelName = '';
                this.getPage();
            }
        });
    }

    /**
     * 删除导入文件
     */
    delFile() {
        this.fileListImport = [];
        this.importExcelName = '';
    }

    /**
     * 文件上传前
     * @ param file
     */
    beforeUploadExcel = (file: UploadFile): boolean => {
        this.fileListImport = [];
        this.fileListImport.push(file);
        this.importExcelName = file.name;
        return false;
    };


}

export class StudentObj {
    classId?: string;
    className?: string;
    collegeId?: string;
    collegeName?: string;
    examStutas?: number;
    id?: string;
    majorId?: string;
    majorName?: string;
    name?: string;
    number?: string;
    photo?: string;
    schoolTime?: string;
    telphone?: string;
    sex = 0;
    type = 0;
    idcard?: string;
    email?: string;
    photoSource: any;
    xqmc: any;
}
